//
//  SgyPhotosListViewController.m
//  PAChat
//
//  Created by ShiMac on 15/6/2.
//  Copyright (c) 2015年 FreeDo. All rights reserved.
//

#import "SgyPhotosListViewController.h"
#import "SgyPhotoGridViewController.h"
#import "SgyListTableViewCell.h"
#define cellHeight 80


#define Column  4
#define capWidth 2

@interface SgyPhotosListViewController ()

@property (strong)      PHFetchResult *allPhotos;            //所有照片
@property (strong)   NSMutableArray *photoMutAry;             //照片组集合

@end

@implementation SgyPhotosListViewController

-(id)init
{
    if (self=[super init]) {
        
        //默认最近添加,视频
        self.albumTypeAry=@[@(PHAssetCollectionSubtypeSmartAlbumRecentlyAdded),@(PHAssetCollectionSubtypeSmartAlbumVideos)];
        
        
        //所有照片
        PHFetchOptions *options = [[PHFetchOptions alloc] init];
        options.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:NO]];
        _allPhotos= [PHAsset fetchAssetsWithOptions:options];
        
        _photoMutAry=[[NSMutableArray alloc] initWithCapacity:0];
        
        //智能相册
        PHFetchResult *smartPhotos=[PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
        [smartPhotos enumerateObjectsUsingBlock:^(PHAssetCollection *obj, NSUInteger idx, BOOL *stop) {
           
            if([self.albumTypeAry containsObject:@(obj.assetCollectionSubtype)]){
                
                PHFetchResult *countResult = [PHAsset fetchAssetsInAssetCollection:obj options:options];
                if (countResult.count > 0) {
                    
                    [_photoMutAry addObject:obj];
                }
            }

        }];
        
        //用户自定义相册
        PHFetchResult *userPhotos=[PHCollectionList fetchTopLevelUserCollectionsWithOptions:nil];
        [userPhotos enumerateObjectsUsingBlock:^(PHAssetCollection *obj, NSUInteger idx, BOOL *stop) {
            
            PHFetchResult *countResult = [PHAsset fetchAssetsInAssetCollection:obj options:options];
            if (countResult.count > 0) {
                [_photoMutAry addObject:obj];
            }
        }];
    }
    return self;
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    self.title=@"照片";
    self.tableView.tableFooterView=[[UIView alloc]initWithFrame:CGRectZero];
    self.tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    
    self.navigationItem.leftBarButtonItem=[[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStyleDone target:self action:@selector(backAction)];
}

-(void)backAction
{
    
    [self dismissViewControllerAnimated:YES completion:nil];
    
}

- (void)didReceiveMemoryWarning {
    
    [super didReceiveMemoryWarning];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return _photoMutAry.count+1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return cellHeight;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    SgyListTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        
        cell=[[SgyListTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
        cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;

    }else{
        
        cell.imageV1.image=nil;
        cell.imageV2.image=nil;
        cell.imageV3.image=nil;
        cell.label.text=nil;
        cell.videoIcon.hidden=YES;
    }

    NSMutableArray *photoAry=[[NSMutableArray alloc]initWithCapacity:0];
    
    if (indexPath.row==0) {
        
        cell.label.text = [NSString stringWithFormat:@"所有照片 (%lu)",(unsigned long)[_allPhotos count]];
        
        [_allPhotos enumerateObjectsUsingBlock:^(PHAsset *obj, NSUInteger idx, BOOL *stop) {
            
            if (idx<3 && obj) {
                
                [photoAry addObject:obj];
                
                
            }
            
        }];
        
    } else {
   
        PHAssetCollection *collection=[_photoMutAry objectAtIndex:indexPath.row-1];
        NSString *localizedTitle = collection.localizedTitle;
        
        PHFetchResult *assetsFetchResult = [PHAsset fetchAssetsInAssetCollection:collection options:nil];
        cell.label.text = [NSString stringWithFormat:@"%@ (%lu)",localizedTitle,(unsigned long)assetsFetchResult.count];
        
        [assetsFetchResult enumerateObjectsUsingBlock:^(PHAsset *obj, NSUInteger idx, BOOL *stop) {
            
            if (idx<3 && obj) {
                
                [photoAry addObject:obj];
                
                
            }
            
        }];

    }
    
 
    [photoAry enumerateObjectsUsingBlock:^(PHAsset *obj, NSUInteger idx, BOOL *stop) {
        
        [[PHImageManager defaultManager] requestImageForAsset:obj
                                                   targetSize:CGSizeMake(60 *[UIScreen mainScreen].scale, 60 *[UIScreen mainScreen].scale)
                                                  contentMode:PHImageContentModeAspectFill
                                                      options:nil
                                                resultHandler:^(UIImage *result, NSDictionary *info) {
                                                    
                                                    if (result) {
                                                        
                                                        if (idx==0) {
                                                            
                                                            cell.imageV1.image=result;
                                                            if (obj.mediaType==PHAssetMediaTypeVideo) {
                                                                cell.videoIcon.hidden=NO;
                                                            }
                                                            
                                                        }else if(idx==1)
                                                        {
                                                            cell.imageV2.image=result;

                                                            
                                                        }else if(idx==2)
                                                        {
                                                            cell.imageV3.image=result;

                                                            
                                                        }
                                                        
                                                    }
                                                }];
    }];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    PHFetchResult *result=nil;
    
    if (indexPath.row==0) {
        
        result=_allPhotos;
    } else {
        
        PHAssetCollection *temp=[_photoMutAry objectAtIndex:indexPath.row-1];
        result = [PHAsset fetchAssetsInAssetCollection:temp options:nil];
    }
    
    if ([result count]<1) {
        return;
    }
    
    CGFloat screenWidth=[[UIScreen mainScreen] bounds].size.width;
    
    CGFloat itemLength=(screenWidth-(Column +1) *capWidth)/Column;
    
    UICollectionViewFlowLayout *flowLayout=[[UICollectionViewFlowLayout alloc]init];
    flowLayout.itemSize=CGSizeMake(itemLength, itemLength);
    flowLayout.sectionInset=UIEdgeInsetsMake(capWidth, capWidth,capWidth ,capWidth);
    flowLayout.minimumInteritemSpacing=capWidth;
    flowLayout.minimumLineSpacing=capWidth;
    flowLayout.scrollDirection=UICollectionViewScrollDirectionVertical;

    SgyPhotoGridViewController *alumnController= [[SgyPhotoGridViewController alloc]initWithCollectionViewLayout:flowLayout];
    alumnController.assetsFetchResults=result;
    alumnController.delegate=self.delegate;
    [self.navigationController pushViewController:alumnController animated:YES];
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
